﻿using LiteDb;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;


namespace DidaManager.Native.Download
{
    public class NetworkDownload
    {
        private CancellationTokenSource? _cancellationTokenSource;
        private bool _isDownloading = false;

        public object DownloadViaNetwork(string param)
        {
            try
            {
                // 如果已经在下载中，返回错误
                if (_isDownloading)
                {
                    return ApiResponse.Fail("已有下载任务在进行中");
                }

                // 创建新的取消令牌
                _cancellationTokenSource = new CancellationTokenSource();
                _isDownloading = true;

                // 解析参数
                var downloadUrl = param?.ToString() ?? "";
                if (string.IsNullOrEmpty(downloadUrl))
                {
                    return ApiResponse.Fail("下载URL不能为空");
                }
    
                // 获取download文件夹路径
                string downloadPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "download");
                if (!Directory.Exists(downloadPath))
                {
                    return ApiResponse.Fail("download文件夹不存在，请先生成配置文件");
                }
    
                // 根据配置类型选择要上传的文件
                var filesToUploadConfig = GetFilesByConfigType(downloadPath, ConfigType.Config);
                var filesToUploadHj212 = GetFilesByConfigType(downloadPath, ConfigType.Hj212);
                
                var filesToUpload = new List<FileUploadInfo>();
                filesToUpload.AddRange(filesToUploadConfig);
                filesToUpload.AddRange(filesToUploadHj212);
    
                if (filesToUpload.Count == 0)
                {
                    return ApiResponse.Fail("没有找到要上传的配置文件");
                }
    
                // 上传文件
                var uploadResult = UploadFiles(downloadUrl, filesToUpload, _cancellationTokenSource.Token);
                
                return uploadResult;
            }
            catch (OperationCanceledException)
            {
                return ApiResponse.Success("下载已取消");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"网络下载失败: {ex.Message}");
            }
            finally
            {
                _isDownloading = false;
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = null;
            }
        }
    
        public object StopDownload()
        {
            try
            {
                if (!_isDownloading || _cancellationTokenSource == null)
                {
                    return ApiResponse.Fail("当前没有下载任务在进行");
                }

                // 触发取消操作
                _cancellationTokenSource.Cancel();
                return ApiResponse.Success("已发送停止下载命令");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"停止下载失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据配置类型获取要上传的文件列表
        /// </summary>
        private List<FileUploadInfo> GetFilesByConfigType(string downloadPath, ConfigType configType)
        {
            var filesToUpload = new List<FileUploadInfo>();
            string configTypeTemp = ConfigType.Config.ToString();
            switch (configType)
            {
                case ConfigType.Config:
                    // 上传端口配置
                    AddFileIfExists(filesToUpload, downloadPath, "PORTConfig.json", configTypeTemp);
                    // 上传设备配置
                    AddFileIfExists(filesToUpload, downloadPath, "DEVConfig.json", configTypeTemp);
                    // 上传变量配置
                    AddVariantFiles(filesToUpload, downloadPath, configTypeTemp);
                    // 上传MQTT配置
                    AddFileIfExists(filesToUpload, downloadPath, "MQTTConfig.json", configTypeTemp);
                    // 上传网络配置
                    AddFileIfExists(filesToUpload, downloadPath, "NetworkConfig.json", configTypeTemp);
                    // 上传MQTT格式配置
                    AddMqttJsonFormatFiles(filesToUpload, downloadPath, configTypeTemp);
                    break;
                case ConfigType.Hj212:
                    // 上传网络配置
                    AddFileIfExists(filesToUpload, downloadPath, "NetworkHj212.json", ConfigType.Hj212.ToString());
                    break;
                case ConfigType.Lua:
                    AddFileIfExists(filesToUpload, downloadPath, "luaScript.lua", configTypeTemp);
                    break;
                case ConfigType.Unknown:
                default:
                    break;
            }
            return filesToUpload;
        }
    
        /// <summary>
        /// 添加变量配置文件
        /// </summary>
        private void AddVariantFiles(List<FileUploadInfo> filesToUpload, string downloadPath, string fieldName)
        {
            // 查找所有VARConfig*.json文件
            string[] variantFiles = Directory.GetFiles(downloadPath, "VARConfig*.json");
            foreach (string filePath in variantFiles)
            {
                string fileName = Path.GetFileName(filePath);
                filesToUpload.Add(new FileUploadInfo
                {
                    FilePath = filePath,
                    FieldName = fieldName,
                    FileName = fileName
                });
            }
        }
        private void AddMqttJsonFormatFiles(List<FileUploadInfo> filesToUpload, string downloadPath, string fieldName)
        {
            // 查找所有Mqtt_*.json文件
            string[] variantFiles = Directory.GetFiles(downloadPath, "Mqtt_*.json");
            foreach (string filePath in variantFiles)
            {
                string fileName = Path.GetFileName(filePath);
                filesToUpload.Add(new FileUploadInfo
                {
                    FilePath = filePath,
                    FieldName = fieldName,
                    FileName = fileName
                });
            }
        }

        /// <summary>
        /// 如果文件存在则添加到上传列表
        /// </summary>
        private void AddFileIfExists(List<FileUploadInfo> filesToUpload, string downloadPath, string fileName, string fieldName)
        {
            string filePath = Path.Combine(downloadPath, fileName);
            if (File.Exists(filePath))
            {
                filesToUpload.Add(new FileUploadInfo
                {
                    FilePath = filePath,
                    FieldName = fieldName,
                    FileName = fileName
                });
            }
        }
    
        /// <summary>
        /// 上传文件到服务器
        /// </summary>
        private object UploadFiles(string downloadUrl, List<FileUploadInfo> filesToUpload, CancellationToken cancellationToken)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    using (var multipartContent = new MultipartFormDataContent())
                    {
                        // 添加每个文件到multipart内容
                        foreach (var fileInfo in filesToUpload)
                        {
                            // 检查是否取消
                            cancellationToken.ThrowIfCancellationRequested();

                            if (File.Exists(fileInfo.FilePath))
                            {
                                var fileContent = new ByteArrayContent(File.ReadAllBytes(fileInfo.FilePath));
                                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                                multipartContent.Add(fileContent, fileInfo.FieldName.ToLower(), fileInfo.FileName);
                            }
                        }
    
                        // 发送请求
                        var response = httpClient.PostAsync(downloadUrl, multipartContent, cancellationToken).Result;
                        
                        if (response.IsSuccessStatusCode)
                        {
                            string responseContent = response.Content.ReadAsStringAsync().Result;
                            return ApiResponse.Success(responseContent, $"成功上传 {filesToUpload.Count} 个配置文件");
                        }
                        else
                        {
                            return ApiResponse.Fail($"上传失败，HTTP状态码: {response.StatusCode}");
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"上传文件失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 文件上传信息
        /// </summary>
        public class FileUploadInfo
        {
            public string FilePath { get; set; } = string.Empty;
            public string FieldName { get; set; } = string.Empty;
            public string FileName { get; set; } = string.Empty;
        }        
    }
}
